﻿using System.Diagnostics;

namespace DimensionsHelper.LanguageService.Syntax;

/// <summary>
///     一元操作符表达式
/// </summary>
public class UnaryExpression : Expression
{
    private Expression _expression;

    internal UnaryExpression(SyntaxToken operatorToken, SyntaxNode? parent) :
        base(SyntaxKinds.UnaryExpression, parent)
    {
        Operator = operatorToken;
        _expression = EmptyExpression.Default;
    }


    /// <summary>
    ///     一元操作符
    /// </summary>
    public SyntaxToken Operator { get; }


    /// <summary>
    ///     一元操作符后的表达式
    /// </summary>
    public Expression Expression => _expression;


    /// <summary>
    ///     更新一元表达式的表达式
    /// </summary>
    /// <param name="expression"></param>
    public UnaryExpression Update(Expression expression)
    {
        if (!expression.IsEmpty)
        {
            SetChildField(ref _expression, IsEmptyExpression, expression);
        }

        return this;
    }


    public override void AcceptVisitor<T>(SyntaxNodeVisitor<T> visitor)
    {
        Accept(visitor, Operator, Expression);
        base.AcceptVisitor(visitor);
    }
}


public static partial class NodeFactory
{
    public static UnaryExpression CreateUnaryExpression(SyntaxNode? parent, SyntaxToken operatorToken,
        Expression expression)
    {
        Debug.Assert(SyntaxFacts.IsUnaryOperatorUnchecked(operatorToken.Kind));
        UnaryExpression unaryExpression = new(operatorToken, parent);
        return unaryExpression.Update(expression);
    }


    public static UnaryExpression CreateUnaryExpression(SyntaxToken operatorToken, Expression expression)
    {
        return CreateUnaryExpression(null, operatorToken, expression);
    }
}